﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Configuration;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;
using System.Xml;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Web.UI.WebControls;


namespace CommonUtility
{
    public class Common
    {
        /// <summary>
        /// 是否是数字
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsNumeric(string value)
        {
            if (string.IsNullOrEmpty(value.Trim()))
                return false;
            else
                return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");
        }

        /// <summary>
        /// 判断是否是日期
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsDate(string value)
        {
            bool result = true;
            try
            {
                DateTime.Parse(value);
            }
            catch
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="_str">被验证数据</param>
        /// <param name="_alidItem">正则表达式</param>
        /// <returns></returns>
        public static bool IsValidString(string _str, string _validItem)
        {
            return Regex.IsMatch(_str, _validItem);
        }

        /// <summary>
        /// 把任意的变量转换成字符串，如果是null或者DBNull.Value，返回String.Empty
        /// </summary>
        /// <param name="_obj">任意变量</param>
        /// <returns>字符串，至少是String.Empty</returns>
        public static string ToString(object _obj)
        {
            string m_Result = String.Empty;

            if (_obj == DBNull.Value || _obj == null)
            {
                m_Result = String.Empty;
            }
            else
            {
                m_Result = Convert.ToString(_obj);
            }

            return m_Result;
        }

        /// <summary>
        /// 把任意的变量转换成整形，如果该变量不能转换成整形，返回0
        /// </summary>
        /// <param name="_obj">任意变量</param>
        /// <returns>整形，至少是0</returns>
        public static int ToInt32(object _obj)
        {
            int m_Result = 0;

            try
            {
                m_Result = Convert.ToInt32(_obj);
            }
            catch (Exception)
            {
                m_Result = 0;
            }

            return m_Result;
        }

        /// <summary>
        ///  把任意的变量转换成长整形，如果该变量不能转换成整形，返回0
        /// </summary>
        /// <param name="_obj">任意变量</param>
        /// <returns>整形，至少是0</returns>
        public static long ToInt64(object _obj)
        {
            long m_Result = 0;

            try
            {
                m_Result = Convert.ToInt64(_obj);
            }
            catch (Exception)
            {
                m_Result = 0;
            }

            return m_Result;
        }

        /// <summary>
        /// 把任意的变量转换为double形，如果该变量不能转换为double,返回0
        /// </summary>
        /// <param name="_obj"></param>
        /// <returns></returns>
        public static double ToDouble(object _obj)
        {
            Double m_Result = 0;

            try
            {
                m_Result = Convert.ToDouble(_obj);
            }
            catch (Exception)
            {
                m_Result = 0;
            }

            return m_Result;
        }

        /// <summary>
        /// 把任意的变量转换为decimal形，如果该变量不能转换为decimal,返回0
        /// </summary>
        /// <param name="_obj"></param>
        /// <returns></returns>
        public static decimal ToDecimal(object _obj)
        {
            decimal m_Result = 0;

            try
            {
                m_Result = Convert.ToDecimal(_obj);
            }
            catch (Exception)
            {
                m_Result = 0;
            }

            return m_Result;
        }

        /// <summary>
        /// 把任意的变量装换成布尔，如果该变量不能转换成布尔，返回false
        /// </summary>
        /// <param name="_obj">任意变量</param>
        /// <returns>布尔，至少是false</returns>
        public static bool ToBoolean(object _obj)
        {
            bool m_Result = false;

            try
            {
                m_Result = Convert.ToBoolean(_obj);
            }
            catch (Exception)
            {
                m_Result = false;
            }

            return m_Result;
        }

        /// <summary>
        /// 转换Json的特殊字符
        /// </summary>
        /// <param name="value">String对象</param>
        /// <returns>Json字符串</returns>
        public static string ToJosn(string _value)
        {
            if (string.IsNullOrEmpty(_value))
            {
                return string.Empty;
            }

            string temstr;
            temstr = _value;
            temstr = temstr.Replace("&nbsp;&nbsp;", "");
            temstr = temstr.Replace("{", "｛");
            temstr = temstr.Replace("}", "｝");
            temstr = temstr.Replace(":", "：");
            temstr = temstr.Replace(",", "，");
            temstr = temstr.Replace("[", "【");
            temstr = temstr.Replace("]", "】");
            temstr = temstr.Replace(";", "；");
            temstr = temstr.Replace("\n", "<br/>");
            temstr = temstr.Replace("\r", "");
            temstr = temstr.Replace("\t", "   ");
            temstr = temstr.Replace("'", "’");
            temstr = temstr.Replace(@"\", @"\\");
            temstr = temstr.Replace("\"", "“");
            temstr = temstr.Replace("\"", "”");
            return temstr;
        }

        /// <summary>
        /// 返回一个32位 Guid 如 “FDKSDFJ32LK3W24SDD5F4SD56FS35F4S”全球唯一标示符
        /// </summary>
        /// <returns></returns>
        public static string GetGUID()
        {
            return System.Guid.NewGuid().ToString().Replace("-", "").ToUpper();
        }

        public static string GetRealIP()
        {
            string ip = string.Empty;
            HttpRequest request = HttpContext.Current.Request;
            try
            {
                if (request.ServerVariables["HTTP_VIA"] != null)
                {
                    ip = request.ServerVariables["HTTP_HOST"].ToString();
                }
                else
                {
                    ip = request.UserHostAddress;
                }
            }
            catch (Exception e)
            {
                //throw e;
            }
            finally
            {
                if (string.IsNullOrEmpty(ip))
                    ip = request.UserHostAddress;
            }
            return ip;
        }

        ///<summary>
        ///防止SQL注入式攻击
        ///</summary>
        ///<param name="inputString">where条件</param>
        public static string ConvertSql(string inputString)
        {
            inputString = inputString.ToLower();
            inputString = inputString.Trim(); //去空格
            inputString = inputString.Replace("'", ""); //去单引号
            inputString = inputString.Replace(";", ""); //去分号
            inputString = inputString.Replace("=", ""); //去等号
            inputString = inputString.Replace(" or ", ""); //去 or
            inputString = inputString.Replace(" and ", ""); //去 and
            inputString = inputString.Replace(" like ", ""); //去 通配符
            inputString = inputString.Replace(";--", ""); //去注释
            inputString = inputString.Replace("insert ", "").Replace("insert/**/", ""); //去插入语句
            inputString = inputString.Replace("update ", "").Replace("update/**/", ""); //去修改语句
            inputString = inputString.Replace("delete ", "").Replace("delete/**/", ""); //去删除语句
            inputString = inputString.Replace("create ", "").Replace("create/**/", ""); //去新建语句
            inputString = inputString.Replace("exec ", "").Replace("exec/**/", ""); //去执行语句
            inputString = inputString.Replace("drop ", "").Replace("drop/**/", ""); //去删除语句
            inputString = inputString.Replace("truncate ", ""); //去清表语句
            inputString = inputString.Replace("xp_cmdshell", ""); //
            return inputString;
        }

        /// <summary>
        /// 运行程序报错时记录错误日志
        /// </summary>
        /// <param name="_methodName">方法路径名称</param>
        /// <param name="_ex">错误</param>
        public static void Application_Error_Server(string _methodName, Exception _ex)
        {
            try
            {
                //尝试记录出错的信息
                //初始化记录出错的xml文件
                if (!File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "/log.xml"))
                {
                    StreamWriter sw = File.CreateText(System.AppDomain.CurrentDomain.BaseDirectory + "/log.xml");
                    sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                    sw.WriteLine("<?xml-stylesheet type=\"text/xsl\" href=\"log.xsl\"?>");
                    sw.WriteLine("<Root></Root>");
                    sw.Close();
                }

                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(System.AppDomain.CurrentDomain.BaseDirectory + "/log.xml");

                XmlElement xRoot = xDoc.DocumentElement;
                XmlNode ndeError = xDoc.CreateNode(XmlNodeType.Element, "Error", "");
                XmlNode ndeTime = xDoc.CreateNode(XmlNodeType.Element, "Time", "");
                ndeTime.InnerText = System.DateTime.Now.ToString("F");
                XmlNode ndeUrl = xDoc.CreateNode(XmlNodeType.Element, "Url", "");
                ndeUrl.InnerText = "后台程序";
                XmlNode ndeDoMainID = xDoc.CreateNode(XmlNodeType.Element, "DoMainID", "");
                ndeDoMainID.InnerText = "";
                XmlNode ndeBugGuid = xDoc.CreateNode(XmlNodeType.Element, "BugGuid", "");
                ndeBugGuid.InnerText = GetGUID();
                XmlNode ndeIp = xDoc.CreateNode(XmlNodeType.Element, "Ip", "");
                ndeIp.InnerText = "服务器";
                XmlNode ndeUser = xDoc.CreateNode(XmlNodeType.Element, "User", "");
                ndeUser.InnerText = _methodName;
                XmlNode ndeContent = xDoc.CreateNode(XmlNodeType.Element, "Content", "");
                XmlNode ndeContentData = xDoc.CreateNode(XmlNodeType.CDATA, "", "");
                ndeContentData.InnerText = _ex.Message + "\r\n" + _ex.StackTrace;

                xRoot.PrependChild(ndeError);
                ndeError.AppendChild(ndeTime);
                ndeError.AppendChild(ndeUrl);
                ndeError.AppendChild(ndeDoMainID);
                ndeError.AppendChild(ndeBugGuid);
                ndeError.AppendChild(ndeContent);
                ndeError.AppendChild(ndeIp);
                ndeError.AppendChild(ndeUser);
                ndeContent.AppendChild(ndeContentData);

                //限制出错记录为1000以下
                while (xRoot.ChildNodes.Count >= 1000)
                    xRoot.RemoveChild(xRoot.LastChild);

                xDoc.Save(System.AppDomain.CurrentDomain.BaseDirectory + "/log.xml");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }




        public static string RandomName(string FileName)
        {
            string StrReturn = FileName;
            StrReturn += DateTime.Now.ToString("yyyyMMddhhmmss");
            StrReturn += "_";
            StrReturn += new Random().Next(1000000, 99999999).ToString();
            StrReturn += System.IO.Path.GetExtension(FileName);
            return StrReturn;
        }

        ////--------------------------------------------------------------------------------------------------------------------------------------------------------
        //public static void MailTo(string _toMail, string _title, string _content, SystemConfig _config)
        //{

        //    if (!string.IsNullOrEmpty(_toMail))
        //    {
        //        try
        //        {
        //            _toMail = _toMail.Replace("，", ",").Trim().Trim(',').Trim();
        //            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
        //            client.Host = "mail.teczs.com";
        //            client.UseDefaultCredentials = true;

        //            client.Credentials = new System.Net.NetworkCredential(_config.Email, _config.Password);
        //            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

        //            string[] arrMail = _toMail.Split(',');
        //            foreach (string mail in arrMail)
        //            {
        //                if (!string.IsNullOrEmpty(mail))
        //                {
        //                    try
        //                    {
        //                        System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(_config.Email, mail);
        //                        message.Subject = _title;
        //                        message.Body = _content;
        //                        message.BodyEncoding = System.Text.Encoding.UTF8;
        //                        message.IsBodyHtml = true;
        //                        client.Send(message);
        //                        TraceApp(mail + "\t\t" + _title);
        //                    }
        //                    catch (Exception exx)
        //                    {
        //                        Application_Error_Server("Common/MailTo()\n" + mail + "\n" + _title + "\n" + _content, exx);
        //                        clsOutMail outMail = new clsOutMail();
        //                        outMail.Address = mail;
        //                        outMail.Title = _title;
        //                        outMail.Body = _content;
        //                        outMail.WriteTime = DateTime.Now.ToString();
        //                        outMail.Times = outMail.Times + 1;
        //                        outMail.Add();
        //                    }
        //                }
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            Application_Error_Server("Common/MailTo()\n" + _toMail + "\n" + _title + "\n" + _content, ex);
        //        }
        //    }
        //}

        //public static void ScanMail()
        //{
        //    try
        //    {
        //        SystemConfig config = new SystemConfig();
        //        IList<clsOutMail> mailList = clsOutMail.GetMailList_noSend();
        //        foreach (clsOutMail mail in mailList)
        //        {
        //            try
        //            {
        //                MailTo(mail.Address, mail.Title, mail.Body, config);
        //                mail.Delete();
        //            }
        //            catch (Exception ex1)
        //            {
        //                Application_Error_Server("Common/ScanMail(1)\n" + mail.Address + "\n" + mail.Title + "\n" + mail.Body, ex1);
        //            }
        //        }
        //    }
        //    catch (Exception ex2)
        //    {
        //        Application_Error_Server("Common/ScanMail(2)", ex2);
        //    }
        //}

        //internal static void MailTo()
        //{
        //    throw new Exception("The method or operation is not implemented.");
        //}

        public static void TraceApp(String _message)
        {
            try
            {
                if (!File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "/TraceLog.txt"))
                    File.Create(System.AppDomain.CurrentDomain.BaseDirectory + "/TraceLog.txt");

                StreamWriter writer = new StreamWriter(System.AppDomain.CurrentDomain.BaseDirectory + "/TraceLog.txt", true, System.Text.Encoding.UTF8);
                writer.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "\t" + _message);
                writer.Flush();
                writer.Close();
                writer.Dispose();
                writer = null;
            }
            catch (System.Exception ex)
            {
                Application_Error_Server("记录应用程序跟踪日志", ex);
            }
        }
    }

}
